package lumis.portal.filesystem;

import lumis.portal.PortalContext;
import lumis.portal.stability.StableMinor;

/**
 * Specifies a portal standard base folder. Also provides conversions between
 * relative paths and absolute paths for each base folder.
 *
 * @version $Revision: 13082 $ $Date: 2011-05-27 16:03:12 -0300 (Fri, 27 May 2011) $
 * @since 4.1.0
 */
@StableMinor(version = "6.0", sinceVersion = "4.1")
public enum PortalBaseFolder
{
	/**
	 * Indicates the path is relative to the portal WWW (web root) folder.
	 * @since 4.1.0
	 */
	WWW, 
	/**
	 * Indicates the path is relative to the portal data (lumisdata/data) folder.
	 * @since 4.1.0
	 */
	DATA, 
	/**
	 * Indicates the path is relative to the portal definition (lumisdata/def) folder.
	 * @since 4.1.0
	 */
	DEF;

	/**
	 * Calculates the absolute path from a relative path to this base folder.
	 * @param relativePath the relative path.
	 * @return the absolute path.
	 * @since 4.1.0
	 */
	public String getAbsolutePath(String relativePath)
	{
		String absolutePath;
		switch(this)
		{
			case WWW:
				absolutePath = PortalContext.getRealPath(relativePath);
				break;
			case DATA:
				absolutePath = PortalContext.getDataPath(relativePath);
				break;
			case DEF:
				absolutePath = PortalContext.getDefinitionPath(relativePath);
				break;
			default:
				throw new IllegalStateException("Unknown BaseFolder: " + this);
		}
		return absolutePath;
	}

	/**
	 * Calculates the relative path to this base folder from the given 
	 * absolute path.
	 * @param absolutePath the absolute path.
	 * @return the calculated relative path, relative to this base folder.
	 * @throws IllegalArgumentException if the given absolute path is invalid 
	 * or does not belongs to this base folder area. 
	 * @since 4.1.0
	 */
	public String getRelativePath(String absolutePath)
	{
		if (absolutePath == null)
			throw new IllegalArgumentException("absolutePath may not be null");
		
		absolutePath = absolutePath.replaceAll("\\\\", "/");
		String rootPath = getAbsolutePath("");
		if (absolutePath.startsWith(rootPath))
		{
			String relativePath = absolutePath.substring(rootPath.length());
			if (relativePath.startsWith("/"))
				relativePath = relativePath.substring(1);
			return relativePath;
		}
		else
		{
			throw new IllegalArgumentException("Could not convert '" + absolutePath + "' to a relativePath of " + this);
		}
	}
}